/**
 * 模块依赖管理器
 * 确保关键模块正确加载后再初始化功能
 */
class ModuleDependencyManager {
    constructor() {
        this.requiredModules = {
            'ApiService': {
                globalName: 'ApiService',
                readyFlag: '_isReady',
                timeout: 5000,
                checkInterval: 100
            },
            'ErrorHandler': {
                globalName: 'ErrorHandler',
                readyFlag: '_isReady',
                timeout: 5000,
                checkInterval: 100
            },
            'NotificationService': {
                globalName: 'NotificationService',
                readyFlag: '_isReady',
                timeout: 5000,
                checkInterval: 100
            }
        };
        this.moduleStates = {};
        this.initCallbacks = [];
    }

    /**
     * 检查模块是否已就绪
     */
    async waitForModule(moduleName, options = {}) {
        const config = { ...this.requiredModules[moduleName], ...options };
        const startTime = Date.now();

        return new Promise((resolve, reject) => {
            const checkModule = () => {
                const module = window[config.globalName];

                if (module && (config.readyFlag === undefined || module[config.readyFlag])) {
                    console.log(`✅ 模块 ${moduleName} 已就绪`);
                    this.moduleStates[moduleName] = 'ready';
                    resolve(true);
                    return;
                }

                if (Date.now() - startTime > config.timeout) {
                    console.error(`❌ 模块 ${moduleName} 加载超时`);
                    this.moduleStates[moduleName] = 'timeout';
                    reject(new Error(`模块 ${moduleName} 加载超时`));
                    return;
                }

                setTimeout(checkModule, config.checkInterval);
            };

            checkModule();
        });
    }

    /**
     * 等待所有必需模块就绪
     */
    async waitForAllRequiredModules() {
        console.log('🔍 开始检查模块依赖...');

        try {
            await Promise.all(
                Object.keys(this.requiredModules).map(moduleName =>
                    this.waitForModule(moduleName)
                )
            );

            console.log('✅ 所有必需模块已就绪');
            return true;
        } catch (error) {
            console.error('❌ 模块依赖检查失败:', error);
            return false;
        }
    }

    /**
     * 添加初始化回调
     */
    onReady(callback) {
        this.initCallbacks.push(callback);
    }

    /**
     * 触发初始化回调
     */
    triggerInitCallbacks() {
        console.log(`🚀 触发 ${this.initCallbacks.length} 个初始化回调`);
        this.initCallbacks.forEach(callback => {
            try {
                callback();
            } catch (error) {
                console.error('初始化回调执行失败:', error);
            }
        });
    }

    /**
     * 获取模块状态
     */
    getModuleStatus() {
        return { ...this.moduleStates };
    }

    /**
     * 强制标记模块为就绪（用于兼容旧代码）
     */
    markModuleReady(moduleName) {
        if (this.requiredModules[moduleName]) {
            const config = this.requiredModules[moduleName];
            const module = window[config.globalName];
            if (module) {
                module[config.readyFlag] = true;
                this.moduleStates[moduleName] = 'ready';
                console.log(`📌 手动标记模块 ${moduleName} 为就绪状态`);
            }
        }
    }
}

// 创建全局实例
window.ModuleDependencyManager = new ModuleDependencyManager();

// 向后兼容：为现有模块添加就绪标记
if (window.ErrorHandler) {
    window.ErrorHandler._isReady = true;
    console.log('ErrorHandler模块已标记为就绪');
}

if (window.NotificationService) {
    window.NotificationService._isReady = true;
    console.log('NotificationService模块已标记为就绪');
}

console.log('ModuleDependencyManager已初始化');